package com.tianyuan.lims.dms.controller.app;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;
import com.jfinal.render.Render;
import com.jfinal.render.RenderException;
import com.tianyuan.lims.common.config.CaptchaConfig;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

/**
 * 图片验证码（支持算术形式）
 * JFinal 版本实现
 */
public class CaptchaController extends Controller {

    /**
     * 验证码生成接口
     * 对应路径：/captcha/captchaImage
     */
//    public void captchaImage() {
//
//        // 获取普通验证码实例
//        Producer captchaProducer = CaptchaConfig.getCaptchaProducer();
//        // 或获取数学验证码实例
//        Producer captchaProducerMath = CaptchaConfig.getCaptchaProducerMath();
//
//        HttpServletRequest request = getRequest();
//        HttpServletResponse response = getResponse();
//        ServletOutputStream out = null;
//
//        try {
//            // 设置响应头，禁止缓存
//            response.setDateHeader("Expires", 0);
//            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
//            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
//            response.setHeader("Pragma", "no-cache");
//            //response.setContentType("image/jpeg");
//            response.setContentType("application/json");
//            // 获取验证码类型（math/char）
//            String type = getPara("type");
//            String capStr = null;
//            String code = null;
//            BufferedImage bi = null;
//
//            if ("math".equals(type)) {
//                // 算术验证码逻辑
//                String capText = captchaProducerMath.createText();
//                capStr = capText.substring(0, capText.lastIndexOf("@"));
//                code = capText.substring(capText.lastIndexOf("@") + 1);
//                bi = captchaProducerMath.createImage(capStr);
//            } else if ("char".equals(type)) {
//                // 字符验证码逻辑
//                capStr = code = captchaProducer.createText();
//                bi = captchaProducer.createImage(capStr);
//            }
//
//            // 将验证码存入 session（JFinal 的 getSession() 等价于 HttpSession）
//            getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, code);
//
//            // 输出图片流
//            out = response.getOutputStream();
//            ImageIO.write(bi, "jpg", out);
//            out.flush();
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (out != null) {
//                    out.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//        // JFinal 中无需返回 ModelAndView，直接通过输出流响应，此处用 renderNull() 结束请求
//        renderNull();
//    }


    public void captchaImage() {
        Producer captchaProducer = CaptchaConfig.getCaptchaProducer();
        Producer captchaProducerMath = CaptchaConfig.getCaptchaProducerMath();
        HttpServletResponse response = getResponse();
        ByteArrayOutputStream baos = null;
        try {
            // 禁用缓存（保持不变）
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("application/json"); // 改为返回JSON

            String type = getPara("type");
            String capStr = null;
            String code = null;
            BufferedImage bi = null;

            if ("math".equals(type)) {
                String capText = captchaProducerMath.createText();
                capStr = capText.substring(0, capText.lastIndexOf("@"));
                code = capText.substring(capText.lastIndexOf("@") + 1);
                bi = captchaProducerMath.createImage(capStr);
            } else {
                capStr = code = captchaProducer.createText();
                bi = captchaProducer.createImage(capStr);
            }

            // 存入session（保持不变）
            getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, code);

            // 将图片转为Base64
            baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64Image = "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(imageBytes);

            // 返回JSON数据（包含验证码图片和是否启用标识）
            renderJson(new HashMap<String, Object>() {{
                put("captchaEnabled", true); // 根据实际逻辑设置是否启用
                put("data", base64Image);
            }});

        } catch (Exception e) {
            e.printStackTrace();
            renderJson(new HashMap<String, Object>() {{
                put("captchaEnabled", false);
                put("error", "获取验证码失败");
            }});
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}